//
//  CMCommon.m
//  CardManage
//
//  Created by 斌 on 2017/11/4.
//  Copyright © 2017年 mupay. All rights reserved.
//

#import "CMCommon.h"
#import <UMSocialCore/UMSocialCore.h>
@implementation CMCommon

//获取文本宽度
+ (CGFloat)getStringWidthWithLabel:(UILabel *)label{
    
    CGSize size = [label.text boundingRectWithSize:CGSizeMake(MAXFLOAT, 0.00)
                                           options:NSStringDrawingUsesLineFragmentOrigin
                                        attributes:@{NSFontAttributeName:label.font}
                                           context:nil].size;
    return size.width;
}


//根据银行名获取银行图片
+ (NSString *)conversionBankImgNameWithBankCode:(NSString*)strBankCode style:(BankImageStyle)style{
    
    NSArray *bankList = @[@"BOB",@"ICBC",@"CEB",@"CGB",@"GDB",
                          @"HXB",@"COMM",@"CMBC",@"ABC",
                          @"SPABANK",@"SPDB",@"SHBANK",@"CIB",
                          @"PSBC",@"CMB",@"BOC",@"CITIC",
                          @"BOHC",@"BJRCB",@"HZCB",@"CCB",
                          @"BOJ",@"NJCB",@"NBBANK"];
    
    NSArray *bankName = @[@"北京银行",@"工商",@"光大",@"广发",@"广发",
                          @"华夏",@"交通",@"民生",@"农业",
                          @"平安",@"浦发",@"上海银行",@"兴业",
                          @"邮储",@"招商",@"中国银行",@"中信",
                          @"渤海",@"北京农商",@"杭州",@"建设",
                          @"江苏",@"南京",@"宁波"];
    
    NSString *bankImgName = @"";
    for (int i = 0 ; i < bankList.count ; i ++) {
        
        NSString *tempStr = [bankList objectAtIndex:i];
        
        NSRange foundObj = [strBankCode rangeOfString:tempStr options:NSCaseInsensitiveSearch];
        if (foundObj.length > 0) {
            bankImgName = [self conversionBankImgNameWithBankName:[bankName objectAtIndex:i] style:style];
        }
    }
    
    if ([bankImgName isEqualToString:@""]) {
        switch (style) {
            case BankImageStyleIcon:
                bankImgName = @"card_moren";
                break;
            case BankImageStyleSmallIcon:
                bankImgName = @"card_mryh";
                break;
            case BankImageStyleBackground:
                bankImgName = @"card_mr";
                break;
            default:
                break;
        }
    }
    
    return bankImgName;
    
}
+ (NSString *)conversionBankImgNameWithBankName:(NSString*)strBankName style:(BankImageStyle)style{
    
    NSArray *bankList = @[@"北京银行",@"工商",@"光大",@"广东发展",@"广发",
                          @"华夏",@"交通",@"民生",@"农业",
                          @"平安",@"浦东发展",@"浦发",@"上海银行",@"兴业",
                          @"邮政",@"邮储",@"招商",@"中国银行",@"中信实业",@"中信",
                          @"渤海",@"北京农商",@"杭州",@"建设",
                          @"江苏",@"南京",@"宁波"];
    
    NSArray *bankImgList = @[@"card_beijing",@"card_gongshang",@"card_guangda",@"card_guangfa",@"card_guangfa",
                             @"card_huaxia",@"card_jiaotong",@"card_mingsheng",@"card_nongye",
                             @"card_pingan",@"card_pufa",@"card_pufa",@"card_shanghai",@"card_xingye",
                             @"card_youchu",@"card_youchu",@"card_zhaoshang",@"card_zhongguo",@"card_zhongxing",@"card_zhongxing",
                             @"card_bohai",@"card_bjnongshang",@"card_hangzhou",@"card_jianshe",
                             @"card_jiansu",@"card_nanjin",@"card_ningbo"];
    
    NSArray *bankSmallImgList = @[@"card_bjyh",@"card_gsyh",@"card_gdyh",@"card_gfyh",@"card_gfyh",
                                  @"card_hxyh",@"card_jtyh",@"card_msyh",@"card_nyyh",
                                  @"card_payh",@"card_pfyh",@"card_pfyh",@"card_shyh",@"card_xyyh",
                                  @"card_ycyh",@"card_ycyh",@"card_zsyh",@"card_zgyh",@"card_zxyh",@"card_zxyh",
                                  @"card_bhyh",@"card_bjnshyh",@"card_hzyh",@"card_jsyh",
                                  @"card_jsuyh",@"card_njyh",@"card_nbyh"];
    
    NSArray *bankBgImgList = @[@"card_bj",@"card_gs",@"card_gd",@"card_gf",@"card_gf",
                               @"card_hx",@"card_jt",@"card_ms",@"card_ny",
                               @"card_pa",@"card_pf",@"card_pf",@"card_sh",@"card_xy",
                               @"card_yc",@"card_yc",@"card_zs",@"card_zg",@"card_zx",@"card_zx",
                               @"card_bh",@"card_bjns",@"card_hz",@"card_jsh",
                               @"card_jsu",@"card_nj",@"card_nb"];

    NSString *bankImgName = @"";
    for (int i = 0 ; i < bankList.count ; i ++) {
        
        NSString *tempStr = [bankList objectAtIndex:i];
        
        NSRange foundObj=[strBankName rangeOfString:tempStr options:NSCaseInsensitiveSearch];
        if (foundObj.length > 0) {
            switch (style) {
                case BankImageStyleIcon:
                    bankImgName = [bankImgList objectAtIndex:i];
                    break;
                case BankImageStyleSmallIcon:
                    bankImgName = [bankSmallImgList objectAtIndex:i];
                    break;
                case BankImageStyleBackground:
                    bankImgName = [bankBgImgList objectAtIndex:i];
                    break;
                default:
                    break;
            }
        }
    }
    
    if ([bankImgName isEqualToString:@""]) {
        switch (style) {
            case BankImageStyleIcon:
                bankImgName = @"card_moren";
                break;
            case BankImageStyleSmallIcon:
                bankImgName = @"card_mryh";
                break;
            case BankImageStyleBackground:
                bankImgName = @"card_mr";
                break;
            default:
                break;
        }
    }
    
    
    
    return bankImgName;
}

//文本串打星号
+ (NSString *)conversionStarWithString:(NSString *)inputText style:(StarStringStyle)style{
    

    if (!inputText) {
        return @"";
    }
    
    if ([inputText isEqualToString:@""]) {
        return inputText;
    }
    
    NSString *starString = @"";
    int start = 0,length = 0;
    
    switch (style) {
        case StarStringStyleRealName:{
            start = 1;
            length = (int)inputText.length - 1;
        }break;
        case StarStringStyleIDCard:{
            start = 6;
            length = (int)inputText.length - 6 - 4;
        }break;
        case StarStringStyleCardNo:{
            start = 6;
            length = (int)inputText.length - 6 - 4;
        }break;
        case StarStringStyleMobileNo:{
            start = 3;
            length = 4;
        }break;
        default:
            break;
    }
    
    if (start > 0 && length > 0) {
        starString = [inputText stringByReplacingCharactersInRange:NSMakeRange(start, length)
                                                        withString:[self generateStar:length]];

    }else{
        return inputText;
    }
    
    //printf("\n%s\n",[starString UTF8String]);

    return starString;
}

+ (NSString *)generateStar:(int)number{
    
    NSString *star = @"";
    do {
        star = [star stringByAppendingString:@"*"];
    } while (star.length < number);
    
    return star;
}


#pragma mark - file
+ (NSString *)getFilePathWithName:(NSString *)fileName {
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:fileName];
    
    return filePath;
}

+ (void)saveFileWithImage:(UIImage *)image Name:(NSString *)fileName {
    
    NSString *uniquePath = [self getFilePathWithName:fileName];
    [UIImagePNGRepresentation(image) writeToFile:uniquePath atomically:YES];
}

+ (void)deleteFileWithName:(NSString *)fileName {
    
    NSString *filePath = [self getFilePathWithName:fileName];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL blHave = [[NSFileManager defaultManager] fileExistsAtPath:filePath];
    if (!blHave) {
        printf("file : no have");
        return;
    }else {
        printf("file : have");
        BOOL blDele = [fileManager removeItemAtPath:filePath error:nil];
        if (blDele) {
            printf("file : delete success");
        }else {
            printf("file : delete fail");
        }
    }
    
}

/**
 *  ios比较日期大小默认会比较到秒
 *
 *  @param oneDay     第一个时间
 *  @param anotherDay 第二个时间
 *
 *  @return 1 第一个时间靠后  -1 第一个时间靠前  0 两个时间相同
 */

//  入参是NSDate类型
- (int)junc_CompareOneDate:(NSDate *)oneDate withAnotherDate:(NSDate *)anotherDate
{
    NSDateFormatter *df = [[NSDateFormatter alloc]init];
    [df setDateFormat:@"dd-MM-yyyy HH:mm:ss"];
    
    NSString *oneDayStr = [df stringFromDate:oneDate];
    
    NSString *anotherDayStr = [df stringFromDate:anotherDate];
    
    NSDate *dateA = [df dateFromString:oneDayStr];
    
    NSDate *dateB = [df dateFromString:anotherDayStr];
    
    NSComparisonResult result = [dateA compare:dateB];
    
    if (result == NSOrderedAscending)
    {  // oneDate < anotherDate
        return 1;
        
    }else if (result == NSOrderedDescending)
    {  // oneDate > anotherDate
        return -1;
    }
    
    // oneDate = anotherDate
    return 0;
}

//  入参是NSString类型
- (int)junc_CompareOneDateStr:(NSString *)oneDateStr withAnotherDateStr:(NSString *)anotherDateStr
{
    NSDateFormatter *df = [[NSDateFormatter alloc]init];
    
    [df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSDate *dateA = [[NSDate alloc]init];
    
    NSDate *dateB = [[NSDate alloc]init];
    
    dateA = [df dateFromString:oneDateStr];
    
    dateB = [df dateFromString:anotherDateStr];
    
    NSComparisonResult result = [dateA compare:dateB];
    
    if (result == NSOrderedAscending)
    {  // oneDateStr < anotherDateStr
        return 1;
        
    }else if (result == NSOrderedDescending)
    {  // oneDateStr > anotherDateStr
        return -1;
    }
    
    // oneDateStr = anotherDateStr
    return 0;
}

//获取32为随机uuid
+ (NSString *)get32ArcUUID{
    NSDate* date = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a =[date timeIntervalSince1970]*1000;
    NSString *timeString = [NSString stringWithFormat:@"%f", a];
    
    timeString = [timeString stringByAppendingString:[NSString stringWithFormat:@"%d",arc4random()%100000]];
    timeString = [SFCrypto encodeMD5:timeString];
    return timeString;
}

//金钱每三位加一个逗号
+(NSString *)countNumAndChangeformat:(NSString *)num
{
    if([num rangeOfString:@"."].location !=NSNotFound)  {
        NSString *losttotal = [NSString stringWithFormat:@"%.2f",[num floatValue]];//小数点后只保留两位
        NSArray *array = [losttotal componentsSeparatedByString:@"."];
        //小数点前:array[0]
        //小数点后:array[1]
        int count = 0;
        num = array[0];
        long long int a = num.longLongValue;
        while (a != 0)
        {
            count++;
            a /= 10;
        }
        NSMutableString *string = [NSMutableString stringWithString:num];
        NSMutableString *newstring = [NSMutableString string];
        while (count > 3) {
            count -= 3;
            NSRange rang = NSMakeRange(string.length - 3, 3);
            NSString *str = [string substringWithRange:rang];
            [newstring insertString:str atIndex:0];
            [newstring insertString:@"," atIndex:0];
            [string deleteCharactersInRange:rang];
        }
        [newstring insertString:string atIndex:0];
        NSMutableString *newString = [NSMutableString string];
        newString =[NSMutableString stringWithFormat:@"%@.%@",newstring,array[1]];
        return newString;
    }else {
        int count = 0;
        long long int a = num.longLongValue;
        while (a != 0)
        {
            count++;
            a /= 10;
        }
        NSMutableString *string = [NSMutableString stringWithString:num];
        NSMutableString *newstring = [NSMutableString string];
        while (count > 3) {
            count -= 3;
            NSRange rang = NSMakeRange(string.length - 3, 3);
            NSString *str = [string substringWithRange:rang];
            [newstring insertString:str atIndex:0];
            [newstring insertString:@"," atIndex:0];
            [string deleteCharactersInRange:rang];
        }
        [newstring insertString:string atIndex:0];
        return newstring;
    }
}

+ (NSString *)getSign:(NSDictionary *)tempDict{
    
    NSArray *keys = [tempDict allKeys];
    keys = [keys sortedArrayUsingSelector:@selector(compare:)];
    
    NSString *hmac = @"";
    for (id key in keys){
        hmac = [NSString stringWithFormat:@"%@%@=%@&",hmac,key,[tempDict objectForKey:key]];
    }
//    hmac = [NSString stringWithFormat:@"%@key=%@",hmac,[CMBasicData getGuideInfo].md5_key];
    hmac = [SFCrypto encodeMD5:hmac];
    return [hmac lowercaseString];
}

+ (NSString *)getNonceStr{
    
    NSArray *randArray = @[@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"0",@"q",@"w",@"e",@"r",@"t",@"y",@"u",@"i",@"o",@"p",@"a",@"s",@"d",@"f",@"g",@"h",@"j",@"k",@"l",@"z",@"x",@"c",@"v",@"b",@"n",@"m",@"Q",@"W",@"E",@"R",@"T",@"Y",@"U",@"I",@"O",@"P",@"F",@"G",@"H",@"J",@"K",@"L",@"Z",@"X",@"C",@"V",@"B",@"N",@"M"];
    NSMutableString *str = [NSMutableString string];;
    for(int i=0; i<32 ; i++){
        [str appendString:randArray[arc4random() % randArray.count]];
    }
    return str;
}

+ (NSString *)getDate{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    //设置时区,这个对于时间的处理有时很重要
    //例如你在国内发布信息,用户在国外的另一个时区,你想让用户看到正确的发布时间就得注意时区设置,时间的换算.
    //例如你发布的时间为2010-01-26 17:40:50,那么在英国爱尔兰那边用户看到的时间应该是多少呢?
    //他们与我们有7个小时的时差,所以他们那还没到这个时间呢...那就是把未来的事做了
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    [formatter setTimeZone:timeZone];
    NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式
    NSString *nowtimeStr = [formatter stringFromDate:datenow];//----------将nsdate按formatter格式转成nsstring
    NSDate *dateNow2 = [formatter dateFromString:nowtimeStr];
    //    时间转时间戳的方法:
    //    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]];//这两个效果一样
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[dateNow2 timeIntervalSince1970]];//这两个效果一样
    NSLog(@"timeSp:%@",timeSp); //时间戳的值
    return timeSp;
}


+ (NSString *)getChangeMoney:(NSString *)money{
    int m = [money intValue];
    if(m>=1000 && m<10000){
        return [NSString stringWithFormat:@"%d千",m/1000];
    }else if (m>=10000){
        return [NSString stringWithFormat:@"%d万",m/10000];
    }else{
        return [NSString stringWithFormat:@"%d",m];
    }
}


+ (NSString *)umengErrMsg:(NSError *)error {
    
    NSString *errMsg = @"";
    switch (error.code) {
        case UMSocialPlatformErrorType_Unknow:
            errMsg = @"未知错误";
            break;
        case UMSocialPlatformErrorType_NotSupport:
            errMsg = @"分享功能不支持";
            break;
        case UMSocialPlatformErrorType_AuthorizeFailed:
            errMsg = @"授权失败";
            break;
        case UMSocialPlatformErrorType_ShareFailed:
            errMsg = @"分享失败";
            break;
        case UMSocialPlatformErrorType_RequestForUserProfileFailed:
            errMsg = @"请求用户信息失败";
            break;
        case UMSocialPlatformErrorType_ShareDataNil:
            errMsg = @"分享内容为空";
            break;
        case UMSocialPlatformErrorType_ShareDataTypeIllegal:
            errMsg = @"分享内容不支持";
            break;
        case UMSocialPlatformErrorType_CheckUrlSchemaFail:
            errMsg = @"schemaurl错误";
            break;
        case UMSocialPlatformErrorType_NotInstall:
            errMsg = @"用户未安装分享平台应用";
            break;
        case UMSocialPlatformErrorType_Cancel:
            errMsg = @"用户取消操作";
            break;
        case UMSocialPlatformErrorType_NotNetWork:
            errMsg = @"网络异常";
            break;
        case UMSocialPlatformErrorType_SourceError:
            errMsg = @"第三方错误";
            break;
        case UMSocialPlatformErrorType_ProtocolNotOverride:
            errMsg = @"网络异常，code:u2013";
            break;
        case UMSocialPlatformErrorType_NotUsingHttps:
            errMsg = @"网络异常，code:u2014";
            break;
        default:
            break;
    }
    return [@"分享:" stringByAppendingString:errMsg];
}

+ (BOOL)judgeIsEmptyWithString:(NSString *)string
{
    if ([string isKindOfClass:[NSNull class]] || [string isEqualToString:@""] || string == nil || string == NULL || string.length == 0)
    {
        return YES;
    }
    return NO;
}
@end
